package cisdi.mes.sm.rm.daoImpl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import cisdi.mes.sm.rm.dao.RmBaseDao;

@Repository
public class RmBaseDaoImpl extends HibernateDaoSupport implements RmBaseDao{

	@Autowired
	public void setMySessionFactory(SessionFactory sessionFactory){
		super.setSessionFactory(sessionFactory);
	}
	@Override
	public void save(Object entity) throws Exception {
		this.getHibernateTemplate().save(entity);
	}

	@Override
	public void update(Object entity) throws Exception {
		this.getHibernateTemplate().update(entity);
	}

	@Override
	public void delete(Object entity) throws Exception {
		this.getHibernateTemplate().delete(entity);
	}
	
	@Override
	public void delete(ArrayList<?> entities) throws Exception {
		this.getHibernateTemplate().deleteAll(entities);
	}

	@Override
	public void delete(String className, String primaryKey, String... ids) throws Exception {
		String id="";
		for(int i=0;i<ids.length;i++){
			if(i!=0){
				id += "','"+ids[i];
			} else {
				id += ids[i];
			}
		}
		final String hql = "DELETE "+className+" t WHERE t."+primaryKey+" in ('"+id+"')";
		System.out.println("-HQL:"+hql);
		this.getHibernateTemplate().execute(new HibernateCallback<Object>() {

			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				session.createQuery(hql).executeUpdate();
				return null;
			}
		});
	}
	
	@Override
	public List<?> query(String daName) throws Exception {
		// TODO 
		String hql = "from "+daName+" t where 1=1 order by t.id desc";
		return this.getHibernateTemplate().find(hql);
	}
	
	@Override
	public void upload(Object[] entities) throws Exception {
		for(Object entity : entities){
			this.getHibernateTemplate().update(entity);
		}
	}
	@Override
	public List<?> query(String daName, Map<String, String> rulMap)
			throws Exception {
		String hql = "FROM  "+daName+"  t WHERE 1=1 "+" ORDER BY t.id desc";
		Set<Entry<String, String>> set = rulMap.entrySet();
		Iterator<Entry<String, String>> iterator = set.iterator();
		while(iterator.hasNext()){
			Map.Entry<String, String> entry = iterator.next();
			entry.getKey();
			entry.getValue();
		}
		
		return this.getHibernateTemplate().find(hql);
	}
	
}
